"""2048核心算法(面向过程)
    list_merge = [2,0,2,0]
    -- 定义函数,对全局变量list_merge,
       实现零元素移动到末尾功能
       思想：从后向前判断,如果为零则删除,再末尾追加零
       2,0,2,0 --> 2,2,0,0
       2,0,4,2 --> 2,4,2,0

    -- 定义函数,实现合并数字功能
       思想：先调用第一个函数,将零元素移动到末尾
            如果是否相邻相同,则后一个元素累加到前一个元素之上,再删除后面元素,最后末尾补零
       2,2,4,0 --> 4,4,0,0
       2,2,2,0 --> 4,2,0,0
       2,0,2,0 --> 2,2,0,0 --> 4,0,0,0
       2,0,0,2 --> 2,2,0,0 --> 4,0,0,0
       2,2,0,0 --> 4,0,0,0"""
list_merge = [2, 0, 2, 0]


def zero_to_end():
    for i in range(len(list_merge) - 1, -1, -1):
        if list_merge[i] == 0:
            list_merge.remove(list_merge[i])
            list_merge.append(0)


# print(list_merge)
def merge():
    zero_to_end()
    for i in range(len(list_merge) - 1):
        if list_merge[i] == list_merge[i + 1]:
            list_merge[i] += list_merge[i]
            del list_merge[i + 1]
            list_merge.append(0)


# merge()
# print(list_merge)

"""-- 向左移动
# 将map每行交给list_merge,再调用merge函数合并数据"""
map = [
    [2, 0, 0, 2],
    [4, 2, 0, 2],
    [2, 4, 2, 4],
    [0, 4, 0, 4],
]


def left_move():
    global list_merge
    for i in map:
        list_merge = i
        merge()


# left_move()
# print(map)
"""--向右移动
# 将map每行翻转后交给list_merge,
# 再调用merge函数合并数据(操作浅拷贝之后的数据)
# 最后还原(再次翻转)
# 温馨提示：花内存图哦"""


def right_move():
    global list_merge
    for i in map:
        list_merge = i[::-1]
        merge()
        i[::-1] = list_merge


# right_move()
# print(map)

"""--向上移动函数
    矩阵转置 --> 向左移动 --> 矩阵转置

--向下移动函数
    矩阵转置 --> 向右移动 --> 矩阵转置"""


# new_map = [i for i in list(zip(*map))]

def up_move():
    global list_merge
    matrix_transpose()
    left_move()
    matrix_transpose()


def matrix_transpose():
    new_map = [list(i) for i in zip(*map)]
    map[:] = new_map


def down_move():
    global list_merge
    matrix_transpose()
    right_move()
    matrix_transpose()


for i in map:
    print(i)
print("*" * 100)
down_move()
for i in map:
    print(i)

